package com.zhang.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhang.pojo.UserBean;
import com.zhang.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private IUserService userService;

    @RequestMapping("findAll")
    public List<UserBean> findAll(){
        return userService.findAll();
    }

    @RequestMapping("add")
    public String add(@Valid UserBean userBean, BindingResult result) throws JsonProcessingException {
        if (result.hasErrors()){
            List<FieldError> fieldErrors = result.getFieldErrors();
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(fieldErrors);
        }
        userService.add(userBean);
        return "ok";
    }
}
